// 封装http
import $ from 'jquery'
import qs from 'qs'

// export const HTTP_SERVER = 'http://localhost:8080' // 本地
export const HTTP_SERVER = 'https://api.read1000.com' // 正式服务器
// export const HTTP_SERVER = 'http://120.79.251.48:8080' // 测试服务器
// export const HTTP_SERVER = 'http://192.168.2.114:8080' // 本地服务器
export const WEB_CLIENT_PREFIX = '{webclient}' // 统一web前缀

export function urlFix(url) {
  if (!url || url.startsWith('http')) return url;
  if (url.startsWith('/')) {
    return url.startsWith(HTTP_SERVER) ? url : `${HTTP_SERVER}${url}`;
  }
  return `${HTTP_SERVER}/${url}`;
}

export function getJson(url, params) {
  return new Promise((resolve, reject) => {
    $.ajax({
      type: 'GET',
      contentType: 'application/json;charset=utf-8',
      url: `${urlFix(url)}?${qs.stringify(params)}`,
      dataType: 'jsonp',
      jsonpCallback: 'callback',
      /*设置一个回调函数，名字随便取，和服务器返回的函数里的名字相同就行*/
      processData: false,
      success: function (data) {
        resolve(data);
      },
      error: function () {
        reject();
      }
    })
  })
}

export function get(url, params) {
  return new Promise((resolve, reject) => {
    $.ajax({
      type: 'GET',
      contentType: 'application/json;charset=utf-8',
      url: `${urlFix(url)}?${qs.stringify(params)}`,
      processData: false,
      success: function (data) {
        if (data) {
          resolve(JSON.parse(data));
        } else {
          reject()
        }
      },
      error: function () {
        reject();
      }
    })
  })
}

export function getData(url, params) {
  return new Promise((resolve, reject) => {
    $.ajax({
      type: 'GET',
      contentType: 'application/json;charset=utf-8',
      url: `${urlFix(url)}?${qs.stringify(params)}`,
      processData: false,
      success: function (data) {
        if (data) {
          resolve(data);
        }
      },
      error: function () {
        reject();
      }
    })
  })
}

export function post(url, params) {
  return new Promise((resolve, reject) => {
    const requestDataJsonStr = WEB_CLIENT_PREFIX + JSON.stringify(params)

    $.ajax({
      type: 'POST',
      contentType: 'application/json;charset=utf-8',
      url: `${urlFix(url)}`,
      data: requestDataJsonStr,
      dataType: 'json',
      crossDomain: true,
      //jsonpCallback: "callback", /*设置一个回调函数，名字随便取，和服务器返回的函数里的名字相同就行*/
      processData: false,
      success: function (data) {
        resolve(data);
      },
      error: function () {
        reject();
      }
    })
  })
}
